# -*- coding: utf-8 -*-
"""
日志工具模块
提供统一的日志配置和管理功能
"""

import logging
import sys
from pathlib import Path
from typing import Optional
from datetime import datetime


def setup_logging(
    level: str = "INFO",
    log_file: Optional[str] = None,
    format_string: Optional[str] = None,
    enable_console: bool = True
) -> None:
    """
    设置日志配置
    
    Args:
        level: 日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL)
        log_file: 日志文件路径，如果为None则不写入文件
        format_string: 自定义日志格式
        enable_console: 是否启用控制台输出
    """
    # 默认日志格式
    if format_string is None:
        format_string = (
            "%(asctime)s - %(name)s - %(levelname)s - "
            "[%(filename)s:%(lineno)d] - %(message)s"
        )
    
    # 创建格式化器
    formatter = logging.Formatter(format_string)
    
    # 获取根日志器
    root_logger = logging.getLogger()
    root_logger.setLevel(getattr(logging, level.upper()))
    
    # 清除现有处理器
    root_logger.handlers.clear()
    
    # 添加控制台处理器
    if enable_console:
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(formatter)
        root_logger.addHandler(console_handler)
    
    # 添加文件处理器
    if log_file:
        log_path = Path(log_file)
        log_path.parent.mkdir(parents=True, exist_ok=True)
        
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setFormatter(formatter)
        root_logger.addHandler(file_handler)


def get_logger(name: str) -> logging.Logger:
    """
    获取指定名称的日志器
    
    Args:
        name: 日志器名称
        
    Returns:
        logging.Logger: 日志器实例
    """
    return logging.getLogger(name)


class APITestLogger:
    """
    API测试专用日志器
    """
    
    def __init__(self, name: str = "api_test"):
        self.logger = get_logger(name)
    
    def log_request(self, method: str, url: str, headers: dict = None, data: dict = None):
        """记录API请求信息"""
        self.logger.info(f"发送 {method} 请求到 {url}")
        if headers:
            self.logger.debug(f"请求头: {headers}")
        if data:
            self.logger.debug(f"请求数据: {data}")
    
    def log_response(self, status_code: int, response_time: float, response_data: dict = None):
        """记录API响应信息"""
        self.logger.info(f"响应状态码: {status_code}, 响应时间: {response_time:.3f}s")
        if response_data:
            self.logger.debug(f"响应数据: {response_data}")
    
    def log_test_start(self, test_name: str):
        """记录测试开始"""
        self.logger.info(f"开始执行测试: {test_name}")
    
    def log_test_end(self, test_name: str, result: str):
        """记录测试结束"""
        self.logger.info(f"测试完成: {test_name} - 结果: {result}")
    
    def log_assertion(self, assertion: str, result: bool):
        """记录断言结果"""
        status = "通过" if result else "失败"
        level = logging.INFO if result else logging.ERROR
        self.logger.log(level, f"断言 '{assertion}': {status}")
    
    def log_error(self, error: Exception, context: str = ""):
        """记录错误信息"""
        error_msg = f"错误: {str(error)}"
        if context:
            error_msg = f"{context} - {error_msg}"
        self.logger.error(error_msg, exc_info=True)


class TestResultLogger:
    """
    测试结果日志器
    """
    
    def __init__(self, log_file: str = None):
        if log_file is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            log_file = f"logs/test_results_{timestamp}.log"
        
        self.log_file = log_file
        self.logger = get_logger("test_results")
        
        # 设置文件处理器
        log_path = Path(log_file)
        log_path.parent.mkdir(parents=True, exist_ok=True)
        
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        formatter = logging.Formatter(
            "%(asctime)s - %(levelname)s - %(message)s"
        )
        file_handler.setFormatter(formatter)
        
        self.logger.addHandler(file_handler)
        self.logger.setLevel(logging.INFO)
    
    def log_test_suite_start(self, suite_name: str):
        """记录测试套件开始"""
        self.logger.info(f"="*50)
        self.logger.info(f"开始执行测试套件: {suite_name}")
        self.logger.info(f"="*50)
    
    def log_test_suite_end(self, suite_name: str, total: int, passed: int, failed: int):
        """记录测试套件结束"""
        self.logger.info(f"测试套件完成: {suite_name}")
        self.logger.info(f"总计: {total}, 通过: {passed}, 失败: {failed}")
        self.logger.info(f"="*50)
    
    def log_test_case(self, case_name: str, result: str, duration: float, error: str = None):
        """记录测试用例结果"""
        self.logger.info(f"[{result}] {case_name} ({duration:.3f}s)")
        if error:
            self.logger.error(f"错误详情: {error}")


# 默认日志配置
setup_logging(
    level="INFO",
    log_file="logs/api_test.log",
    enable_console=True
)

# 创建默认日志器实例
api_logger = APITestLogger()
result_logger = TestResultLogger()